import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Provide,
  Put,
  Query,
} from '@midwayjs/core';
import { UserService } from '../service/user.service';
import { User } from '../entity/user.entity';
import { UserDTO } from '../dto/user.dto';
import { ParseIntPipe } from '@midwayjs/validate';
import { BadRequestError } from '../error/request.error';
import * as bcrypt from 'bcryptjs';
import { omit } from 'lodash';

@Provide()
@Controller('/user')
export class UserController {
  @Inject()
  private userService: UserService;

  @Post('/')
  async create(@Body() data: UserDTO) {
    const { username, password } = data;
    const userData = await this.userService.findBy({ username });
    if (userData) {
      throw new BadRequestError('该用户已被注册');
    }
    const user = new User();
    user.username = data.username;
    user.password = bcrypt.hashSync(password, 10);
    user.nickname = data.nickname;
    user.phone = data.phone;
    user.status = data.status;
    const result = await this.userService.create(user);
    return omit(result, ['password']);
  }

  @Put('/:id')
  async update(@Param('id', [ParseIntPipe]) id: number, @Body() data: UserDTO) {
    const { password } = data;
    const user = new User();
    user.id = id;
    user.username = data.username;
    user.password = bcrypt.hashSync(password, 10);
    user.nickname = data.nickname;
    user.phone = data.phone;
    user.status = data.status;
    const result = await this.userService.update(user);
    return omit(result, ['password']);
  }

  @Del('/:id')
  async delete(@Param('id', [ParseIntPipe]) id: number) {
    const result = await this.userService.delete(id);
    return result.affected === 1;
  }

  @Get('/:id')
  async info(@Param('id', [ParseIntPipe]) id: number) {
    const user = await this.userService.findBy({ id });
    return omit(user, ['password']);
  }

  @Get('/page')
  async page(
    @Query('offset', [ParseIntPipe]) offset: number,
    @Query('limit', [ParseIntPipe]) limit: number,
    @Query() queryData
  ) {
    const where = omit(queryData, ['offset', 'limit']);
    const [data, total] = await this.userService.findAndCount(
      offset,
      limit,
      where
    );
    return { data, total, offset, limit };
  }
}
